﻿Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Drawing
Imports System.Drawing.Design
Imports System.Globalization
Imports System.IO
Imports System.Reflection
Imports System.Resources
Imports System.Runtime.InteropServices
Imports System.Security.Permissions
Imports System.Text
Imports System.Windows.Forms
Imports System.Windows.Forms.Design
Imports System.Workflow.ComponentModel.Compiler
Imports System.Workflow.Interop

Namespace System.Workflow.ComponentModel.Design
    Public NotInheritable Class TypeBrowserDialog
        Inherits Form
        Implements ISite, IServiceProvider
        ' Methods
        Public Sub New(ByVal serviceProvider As IServiceProvider, ByVal filterProvider As ITypeFilterProvider, ByVal selectedTypeName As String)
            Me.genericParameters = New GenericParameters
            If (serviceProvider Is Nothing) Then
                Throw New ArgumentNullException("serviceProvider")
            End If
            Me.InitializeDialog(serviceProvider, filterProvider, selectedTypeName)
        End Sub

        Public Sub New(ByVal serviceProvider As IServiceProvider, ByVal filterProvider As ITypeFilterProvider, ByVal selectedTypeName As String, ByVal typeProvider As TypeProvider)
            Me.genericParameters = New GenericParameters
            If (serviceProvider Is Nothing) Then
                Throw New ArgumentNullException("serviceProvider")
            End If
            Me.localTypeProvider = typeProvider
            Me.serviceProvider = serviceProvider
            Helpers.AddTypeProviderAssembliesFromRegistry(Me.localTypeProvider, serviceProvider)
            Me.InitializeDialog(serviceProvider, filterProvider, selectedTypeName)
            Me.buttonBrowse.Visible = True
            Me.buttonBrowse.Enabled = True
            Me.buttonBrowse.BringToFront
        End Sub

        Private Sub CustomInitializeComponent()
            MyBase.SuspendLayout
            Me.artifactTreeView.Sorted = True
            Me.bitmapSortUp = [TryCast](TypeBrowserDialog.ResMgr.GetObject("IDB_SORTUP"),Bitmap).GetHbitmap
            Me.bitmapSortDown = [TryCast](TypeBrowserDialog.ResMgr.GetObject("IDB_SORTDOWN"),Bitmap).GetHbitmap
            Me.artifactImages = New ImageList
            Me.artifactImages.TransparentColor = Color.FromArgb(0, &HFF, 0)
            Me.artifactImages.Images.AddStrip(DirectCast(TypeBrowserDialog.ResMgr.GetObject("IDB_ARTIFACTIMAGES"), Image))
            Me.artifactListView.Dock = DockStyle.Fill
            Me.artifactListView.FullRowSelect = True
            Me.artifactListView.HideSelection = False
            Me.artifactListView.MultiSelect = False
            Me.artifactListView.SmallImageList = Me.artifactImages
            AddHandler Me.artifactListView.MouseDown, New MouseEventHandler(AddressOf Me.OnListViewMouseDown)
            Me.artifactTreeView.HideSelection = False
            Me.artifactTreeView.ImageList = Me.artifactImages
            Me.helpTextHolder.Visible = False
            Me.helpTextWindow = New HelpTextWindow
            Me.helpTextWindow.Parent = Me
            Me.helpTextWindow.Location = New Point((Me.helpTextHolder.Location.X + 3), (Me.helpTextHolder.Location.Y + 3))
            Me.helpTextWindow.Size = New Size((Me.helpTextHolder.Size.Width - 6), (Me.helpTextHolder.Size.Height - 6))
            If (Not Me.typeFilterProvider Is Nothing) Then
                Me.artifactLabel.Text = Me.typeFilterProvider.FilterDescription
            End If
            Dim service As IUIService = DirectCast(Me.serviceProvider.GetService(GetType(IUIService)), IUIService)
            If (Not service Is Nothing) Then
                Me.Font = DirectCast(service.Styles.Item("DialogFont"), Font)
            End If
            Me.artifactLabel.Font = New Font(Me.Font.Name, Me.Font.SizeInPoints, FontStyle.Bold)
            Me.genericParametersPropertyGrid.SelectedObject = Me.genericParameters
            Me.genericParametersPropertyGrid.Site = Me
            AddHandler Me.genericParametersPropertyGrid.PropertyValueChanged, New PropertyValueChangedEventHandler(AddressOf Me.GenericParameterChanged)
            MyBase.ResumeLayout(False)
        End Sub

        Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            MyBase.Dispose(disposing)
        End Sub

        Private Sub GenericParameterChanged(ByVal sender As Object, ByVal e As PropertyValueChangedEventArgs)
            Dim flag As Boolean = True
            Dim data As ParameterData
            For Each data In Me.genericParameters.Parameters
                If (data.Type Is Nothing) Then
                    flag = False
                    Exit For
                End If
            Next
            If flag Then
                Me.UpdateTypeTextBox
            End If
        End Sub

        Private Sub GetHelp()
            DesignerHelpers.ShowHelpFromKeyword(Me.serviceProvider, (GetType(TypeBrowserDialog).FullName & ".UI"))
        End Sub

        Private Function GetSimpleTypeFullName(ByVal type As Type) As String
            Dim builder As New StringBuilder(type.FullName)
            Dim stack As New Stack([Of] Type)
            stack.Push(type)
            Do While (stack.Count > 0)
                type = stack.Pop
                Do While type.IsArray
                    type = type.GetElementType
                Loop
                If (type.IsGenericType AndAlso Not type.IsGenericTypeDefinition) Then
                    Dim type2 As Type
                    For Each type2 In type.GetGenericArguments
                        builder.Replace(("[" & type2.AssemblyQualifiedName & "]"), type2.FullName)
                        stack.Push(type2)
                    Next
                End If
            Loop
            Return builder.ToString
        End Function

        Private Sub GetTypeParts(ByVal type As Type, <Out> ByRef baseType As Type, <Out> ByRef parameterDataArray As ParameterData(), <Out> ByRef arrayRanks As Integer())
            baseType = Nothing
            parameterDataArray = Nothing
            arrayRanks = Nothing
            If type.IsArray Then
                Dim list As New ArrayList
                Me.GetTypeParts(type.GetElementType, baseType, parameterDataArray, arrayRanks)
                If (Not arrayRanks Is Nothing) Then
                    list.AddRange(arrayRanks)
                End If
                list.Add(type.GetArrayRank)
                arrayRanks = DirectCast(list.ToArray(GetType(Integer)), Integer())
            ElseIf type.IsGenericType Then
                Dim underlyingSystemType As Type = Nothing
                Dim type3 As Type = Nothing
                If type.ContainsGenericParameters Then
                    type3 = Nothing
                    underlyingSystemType = type.UnderlyingSystemType
                Else
                    type3 = type
                    underlyingSystemType = type.GetGenericTypeDefinition.UnderlyingSystemType
                End If
                Dim list2 As New ArrayList
                Dim i As Integer
                For i = 0 To underlyingSystemType.GetGenericArguments.Length - 1
                    Dim data As New ParameterData { _
                        .ParameterType = underlyingSystemType.GetGenericArguments(i) _
                    }
                    If (Not type3 Is Nothing) Then
                        data.Type = type.GetGenericArguments(i)
                    End If
                    list2.Add(data)
                Next i
                parameterDataArray = DirectCast(list2.ToArray(GetType(ParameterData)), ParameterData())
                baseType = underlyingSystemType
            Else
                baseType = type
            End If
        End Sub

        Private Sub InitializeComponent()
            Dim manager As New ComponentResourceManager(GetType(TypeBrowserDialog))
            Me.buttonCancel = New Button
            Me.helpTextHolder = New TextBox
            Me.buttonOK = New Button
            Me.tabControl = New TabControl
            Me.typeTabPage = New TabPage
            Me.typeSplitContainer = New SplitContainer
            Me.artifactTreeView = New TreeView
            Me.artifactListView = New ListView
            Me.typeName = New ColumnHeader
            Me.fullyQualifiedName = New ColumnHeader
            Me.advancedTabPage = New TabPage
            Me.genericParametersPropertyGrid = New PropertyGrid
            Me.buttonBrowse = New Button
            Me.typeTextBox = New TextBox
            Me.typeNameLabel = New Label
            Me.okCancelTableLayoutPanel = New TableLayoutPanel
            Me.typeNameTableLayoutPanel = New TableLayoutPanel
            Me.artifactLabel = New TextBox
            Me.tabControl.SuspendLayout
            Me.typeTabPage.SuspendLayout
            Me.typeSplitContainer.Panel1.SuspendLayout
            Me.typeSplitContainer.Panel2.SuspendLayout
            Me.typeSplitContainer.SuspendLayout
            Me.advancedTabPage.SuspendLayout
            Me.okCancelTableLayoutPanel.SuspendLayout
            Me.typeNameTableLayoutPanel.SuspendLayout
            MyBase.SuspendLayout
            manager.ApplyResources(Me.buttonCancel, "buttonCancel")
            Me.buttonCancel.DialogResult = DialogResult.Cancel
            Me.buttonCancel.Name = "buttonCancel"
            manager.ApplyResources(Me.helpTextHolder, "helpTextHolder")
            Me.helpTextHolder.BorderStyle = BorderStyle.FixedSingle
            Me.helpTextHolder.Name = "helpTextHolder"
            Me.helpTextHolder.ReadOnly = True
            manager.ApplyResources(Me.buttonOK, "buttonOK")
            Me.buttonOK.DialogResult = DialogResult.OK
            Me.buttonOK.Name = "buttonOK"
            AddHandler Me.buttonOK.Click, New EventHandler(AddressOf Me.OkButtonClicked)
            manager.ApplyResources(Me.tabControl, "tabControl")
            Me.tabControl.Controls.Add(Me.typeTabPage)
            Me.tabControl.Controls.Add(Me.advancedTabPage)
            Me.tabControl.Name = "tabControl"
            Me.tabControl.SelectedIndex = 0
            Me.typeTabPage.BackColor = Color.Transparent
            Me.typeTabPage.Controls.Add(Me.typeSplitContainer)
            manager.ApplyResources(Me.typeTabPage, "typeTabPage")
            Me.typeTabPage.Name = "typeTabPage"
            Me.typeSplitContainer.BackColor = Color.Transparent
            manager.ApplyResources(Me.typeSplitContainer, "typeSplitContainer")
            Me.typeSplitContainer.Name = "typeSplitContainer"
            Me.typeSplitContainer.Panel1.Controls.Add(Me.artifactTreeView)
            Me.typeSplitContainer.Panel2.Controls.Add(Me.artifactListView)
            Me.typeSplitContainer.TabStop = False
            Me.artifactTreeView.BackColor = SystemColors.Window
            manager.ApplyResources(Me.artifactTreeView, "artifactTreeView")
            Me.artifactTreeView.ItemHeight = &H10
            Me.artifactTreeView.Name = "artifactTreeView"
            AddHandler Me.artifactTreeView.AfterSelect, New TreeViewEventHandler(AddressOf Me.OnTreeSelectionChange)
            AddHandler Me.artifactTreeView.GotFocus, New EventHandler(AddressOf Me.OnTreeViewGotFocus)
            Me.artifactListView.AllowColumnReorder = True
            Me.artifactListView.Columns.AddRange(New ColumnHeader() { Me.typeName, Me.fullyQualifiedName })
            manager.ApplyResources(Me.artifactListView, "artifactListView")
            Me.artifactListView.Name = "artifactListView"
            Me.artifactListView.UseCompatibleStateImageBehavior = False
            Me.artifactListView.View = View.Details
            AddHandler Me.artifactListView.SelectedIndexChanged, New EventHandler(AddressOf Me.OnListViewSelectedIndexChanged)
            AddHandler Me.artifactListView.ColumnClick, New ColumnClickEventHandler(AddressOf Me.OnListViewColumnClick)
            manager.ApplyResources(Me.typeName, "typeName")
            manager.ApplyResources(Me.fullyQualifiedName, "fullyQualifiedName")
            Me.advancedTabPage.BackColor = Color.Transparent
            Me.advancedTabPage.Controls.Add(Me.genericParametersPropertyGrid)
            manager.ApplyResources(Me.advancedTabPage, "advancedTabPage")
            Me.advancedTabPage.Name = "advancedTabPage"
            manager.ApplyResources(Me.genericParametersPropertyGrid, "genericParametersPropertyGrid")
            Me.genericParametersPropertyGrid.Name = "genericParametersPropertyGrid"
            Me.genericParametersPropertyGrid.PropertySort = PropertySort.Categorized
            Me.genericParametersPropertyGrid.ToolbarVisible = False
            manager.ApplyResources(Me.buttonBrowse, "buttonBrowse")
            Me.buttonBrowse.Name = "buttonBrowse"
            AddHandler Me.buttonBrowse.Click, New EventHandler(AddressOf Me.OnButtonBrowse_Click)
            manager.ApplyResources(Me.typeTextBox, "typeTextBox")
            Me.typeTextBox.Name = "typeTextBox"
            AddHandler Me.typeTextBox.TextChanged, New EventHandler(AddressOf Me.OnTypeTextBoxTextChanged)
            manager.ApplyResources(Me.typeNameLabel, "typeNameLabel")
            Me.typeNameLabel.Name = "typeNameLabel"
            manager.ApplyResources(Me.okCancelTableLayoutPanel, "okCancelTableLayoutPanel")
            Me.okCancelTableLayoutPanel.Controls.Add(Me.buttonOK, 0, 0)
            Me.okCancelTableLayoutPanel.Controls.Add(Me.buttonCancel, 1, 0)
            Me.okCancelTableLayoutPanel.Name = "okCancelTableLayoutPanel"
            manager.ApplyResources(Me.typeNameTableLayoutPanel, "typeNameTableLayoutPanel")
            Me.typeNameTableLayoutPanel.Controls.Add(Me.typeNameLabel, 0, 0)
            Me.typeNameTableLayoutPanel.Controls.Add(Me.typeTextBox, 1, 0)
            Me.typeNameTableLayoutPanel.Name = "typeNameTableLayoutPanel"
            Me.artifactLabel.BorderStyle = BorderStyle.None
            Me.artifactLabel.CausesValidation = False
            manager.ApplyResources(Me.artifactLabel, "artifactLabel")
            Me.artifactLabel.Name = "artifactLabel"
            Me.artifactLabel.ReadOnly = True
            Me.artifactLabel.TabStop = False
            MyBase.AcceptButton = Me.buttonOK
            manager.ApplyResources(Me, "$this")
            MyBase.CancelButton = Me.buttonCancel
            MyBase.Controls.Add(Me.artifactLabel)
            MyBase.Controls.Add(Me.typeNameTableLayoutPanel)
            MyBase.Controls.Add(Me.okCancelTableLayoutPanel)
            MyBase.Controls.Add(Me.buttonBrowse)
            MyBase.Controls.Add(Me.helpTextHolder)
            MyBase.Controls.Add(Me.tabControl)
            MyBase.FormBorderStyle = FormBorderStyle.FixedDialog
            MyBase.HelpButton = True
            MyBase.MaximizeBox = False
            MyBase.MinimizeBox = False
            MyBase.Name = "TypeBrowserDialog"
            MyBase.ShowInTaskbar = False
            AddHandler MyBase.HelpButtonClicked, New CancelEventHandler(AddressOf Me.TypeBrowserDialog_HelpButtonClicked)
            Me.tabControl.ResumeLayout(False)
            Me.typeTabPage.ResumeLayout(False)
            Me.typeSplitContainer.Panel1.ResumeLayout(False)
            Me.typeSplitContainer.Panel2.ResumeLayout(False)
            Me.typeSplitContainer.ResumeLayout(False)
            Me.advancedTabPage.ResumeLayout(False)
            Me.okCancelTableLayoutPanel.ResumeLayout(False)
            Me.okCancelTableLayoutPanel.PerformLayout
            Me.typeNameTableLayoutPanel.ResumeLayout(False)
            Me.typeNameTableLayoutPanel.PerformLayout
            MyBase.ResumeLayout(False)
            MyBase.PerformLayout
        End Sub

        Friend Sub InitializeDialog(ByVal serviceProvider As IServiceProvider, ByVal filterProvider As ITypeFilterProvider, ByVal selectedTypeName As String)
            Me.serviceProvider = serviceProvider
            Me.sortListViewAscending = True
            Me.refreshTreeView = False
            Me.refreshTypeTextBox = False
            Me.selectedTypeName = selectedTypeName
            Me.typeFilterProvider = filterProvider
            Dim service As IDesignerHost = [TryCast](Me.serviceProvider.GetService(GetType(IDesignerHost)),IDesignerHost)
            Dim loader As WorkflowDesignerLoader = [TryCast](Me.serviceProvider.GetService(GetType(WorkflowDesignerLoader)),WorkflowDesignerLoader)
            If (((service Is Nothing) OrElse (service.RootComponent Is Nothing)) OrElse ((loader Is Nothing) OrElse loader.InDebugMode)) Then
                Throw New Exception(DR.GetString("Error_WorkflowNotLoaded", New Object(0  - 1) {}))
            End If
            Me.InitializeComponent
            Me.CustomInitializeComponent
            Me.genericParametersPropertyGrid.Site = New DummySite(Me.serviceProvider)
        End Sub

        Private Sub ListSelectionChanged(ByVal selectedType As Type)
            If Not Me.artifactTreeView.Focused Then
                Dim fullName As String = selectedType.FullName
                Dim name As String = String.Empty
                If (Not selectedType.Assembly Is Nothing) Then
                    name = selectedType.Assembly.GetName.Name
                End If
                Dim node As TreeNode = Nothing
                If (name.Length = 0) Then
                    node = Me.artifactTreeView.Nodes.Item("CurrentProject")
                Else
                    Dim node2 As TreeNode = Me.artifactTreeView.Nodes.Item("ReferencedAssemblies")
                    Dim node3 As TreeNode
                    For Each node3 In node2.Nodes
                        Dim tag As Assembly = [TryCast](node3.Tag,Assembly)
                        If ((tag.FullName = name) OrElse (tag.GetName.Name = name)) Then
                            node = node3
                            Exit For
                        End If
                    Next
                End If
                Dim node4 As TreeNode = Nothing
                If (Not node Is Nothing) Then
                    Dim str3 As String = String.Empty
                    Dim length As Integer = fullName.LastIndexOf("."c)
                    If (length <> -1) Then
                        str3 = fullName.Substring(0, length)
                    End If
                    If (str3.Length > 0) Then
                        Dim node5 As TreeNode
                        For Each node5 In node.Nodes
                            If (node5.Text = str3) Then
                                node4 = node5
                                Exit For
                            End If
                        Next
                    End If
                End If
                Dim node6 As TreeNode = node4
                If (node6 Is Nothing) Then
                    node6 = node
                End If
                If ((Not node6 Is Nothing) AndAlso Me.artifactTreeView.CanFocus) Then
                    Me.artifactTreeView.SelectedNode = node6
                    node6.EnsureVisible
                End If
            End If
        End Sub

        Private Sub OkButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
            Try 
                Dim type As Type = Me.TypeProvider.GetType(Me.typeTextBox.Text)
                If ((Not type Is Nothing) AndAlso ((Me.typeFilterProvider Is Nothing) OrElse Me.typeFilterProvider.CanFilterType(type, False))) Then
                    Me.selectedTypeName = type.AssemblyQualifiedName
                    Me.selectedType = type
                    MyBase.DialogResult = DialogResult.OK
                Else
                    MyBase.DialogResult = DialogResult.None
                End If
            Catch exception As Exception
                DesignerHelpers.ShowError(Me.serviceProvider, exception)
            End Try
        End Sub

        Private Sub OnButtonBrowse_Click(ByVal Sender As Object, ByVal e As EventArgs)
            Dim handler2 As EventHandler = Nothing
            Dim fileDialog As New OpenFileDialog { _
                .Title = DR.GetString("OpenfileDialogTitle", New Object(0  - 1) {}), _
                .AddExtension = True, _
                .DefaultExt = "dll", _
                .CheckFileExists = True, _
                .CheckPathExists = True, _
                .DereferenceLinks = True, _
                .ValidateNames = True, _
                .Filter = DR.GetString("PackageAssemblyReferenceFilter", New Object(0  - 1) {}), _
                .RestoreDirectory = False _
            }
            If (fileDialog.ShowDialog(Me) = DialogResult.OK) Then
                If (handler2 Is Nothing) Then
                    handler2 = Function (ByVal sender As Object, ByVal ea As EventArgs) 
                        Dim exception As Exception = Nothing
                        If Me.localTypeProvider.TypeLoadErrors.ContainsKey(fileDialog.FileName) Then
                            exception = Me.localTypeProvider.TypeLoadErrors.Item(fileDialog.FileName)
                        End If
                        If (Not exception Is Nothing) Then
                            Dim format As String = If((TypeOf exception Is ReflectionTypeLoadException OrElse ((Not exception.InnerException Is Nothing) AndAlso TypeOf exception.InnerException Is ReflectionTypeLoadException)), DR.GetString("TypeBrowser_UnableToLoadOneOrMoreTypes", New Object(0  - 1) {}), DR.GetString("TypeBrowser_ProblemsLoadingAssembly", New Object(0  - 1) {}))
                            format = String.Format(CultureInfo.CurrentCulture, format, New Object() { fileDialog.FileName })
                            DesignerHelpers.ShowError(Me.serviceProvider, format)
                        End If
                    End Function
                End If
                Dim handler As EventHandler = handler2
                Try 
                    Dim service As ITypeProviderCreator = [TryCast](Me.serviceProvider.GetService(GetType(ITypeProviderCreator)),ITypeProviderCreator)
                    If (Not service Is Nothing) Then
                        Me.localTypeProvider.AddAssembly(service.GetTransientAssembly(AssemblyName.GetAssemblyName(fileDialog.FileName)))
                    Else
                        Me.localTypeProvider.AddAssemblyReference(fileDialog.FileName)
                    End If
                    Helpers.UpdateTypeProviderAssembliesRegistry(fileDialog.FileName)
                    AddHandler Me.localTypeProvider.TypeLoadErrorsChanged, handler
                    Me.UpdateTreeView(Me.localTypeProvider.GetTypes, Me.typeTextBox.AutoCompleteCustomSource)
                Catch exception As FileNotFoundException
                    DesignerHelpers.ShowError(Me.serviceProvider, exception.Message)
                Catch exception3 As BadImageFormatException
                    DesignerHelpers.ShowError(Me.serviceProvider, SR.GetString("Error_AssemblyBadImage", New Object() { fileDialog.FileName }))
                Catch exception4 As FileLoadException
                    DesignerHelpers.ShowError(Me.serviceProvider, SR.GetString("Error_AssemblyBadImage", New Object() { fileDialog.FileName }))
                Catch exception2 As Exception
                    DesignerHelpers.ShowError(Me.serviceProvider, SR.GetString("Error_AddAssemblyRef", New Object() { fileDialog.FileName, exception2.Message }))
                Finally
                    RemoveHandler Me.localTypeProvider.TypeLoadErrorsChanged, handler
                End Try
            End If
        End Sub

        Protected Overrides Sub OnClosing(ByVal e As CancelEventArgs)
            MyBase.OnClosing(e)
            If (IntPtr.Zero <> Me.bitmapSortUp) Then
                NativeMethods.DeleteObject(Me.bitmapSortUp)
            End If
            If (IntPtr.Zero <> Me.bitmapSortDown) Then
                NativeMethods.DeleteObject(Me.bitmapSortDown)
            End If
        End Sub

        Protected Overrides Sub OnHelpRequested(ByVal e As HelpEventArgs)
            e.Handled = True
            Me.GetHelp
        End Sub

        Private Sub OnListViewColumnClick(ByVal sender As Object, ByVal e As ColumnClickEventArgs)
            Me.sortListViewAscending = Not Me.sortListViewAscending
            Me.SortListViewItems(e.Column)
        End Sub

        Private Sub OnListViewMouseDown(ByVal sender As Object, ByVal mouseArgs As MouseEventArgs)
            If (((mouseArgs.Clicks > 1) AndAlso (Me.artifactListView.SelectedItems.Count > 0)) AndAlso (TypeOf Me.artifactListView.SelectedItems.Item(0).Tag Is Type AndAlso Me.buttonOK.Enabled)) Then
                Me.OkButtonClicked(Me.buttonOK, EventArgs.Empty)
            End If
        End Sub

        Private Sub OnListViewSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            Try 
                If (Not Me.refreshTypeTextBox AndAlso (Me.artifactListView.SelectedItems.Count > 0)) Then
                    Me.typeTextBox.Text = [TryCast](Me.artifactListView.SelectedItems.Item(0).Tag,Type).FullName
                End If
                If (Me.artifactListView.SelectedItems.Count > 0) Then
                    Me.artifactListView.SelectedItems.Item(0).EnsureVisible
                End If
                If (Me.artifactListView.Focused AndAlso (Me.artifactListView.SelectedItems.Count <> 0)) Then
                    Dim tag As Type = [TryCast](Me.artifactListView.SelectedItems.Item(0).Tag,Type)
                    If (Not tag Is Nothing) Then
                        Me.ListSelectionChanged(tag)
                    End If
                End If
            Catch exception As Exception
                DesignerHelpers.ShowError(Me.serviceProvider, exception)
            End Try
        End Sub

        Protected Overrides Sub OnLoad(ByVal e As EventArgs)
            MyBase.OnLoad(e)
            Cursor.Current = Cursors.WaitCursor
            Try 
                Dim node As TreeNode = Nothing
                If (Me.localTypeProvider Is Nothing) Then
                    node = Me.artifactTreeView.Nodes.Add("CurrentProject", SR.GetString("CurrentProject"), 2, 2)
                End If
                Dim node2 As TreeNode = Me.artifactTreeView.Nodes.Add("ReferencedAssemblies", SR.GetString("ReferencedAssemblies"), 2, 2)
                Dim typeProvider As ITypeProvider = Me.TypeProvider
                Dim autoCompleteStringCollection As New AutoCompleteStringCollection
                Me.UpdateTreeView(typeProvider.GetTypes, autoCompleteStringCollection)
                node2.Expand
                Dim treeNode As TreeNode = If((node Is Nothing), node2, node)
                Me.artifactTreeView.SelectedNode = treeNode
                Me.TreeSelectionChanged(treeNode)
                treeNode.EnsureVisible
                Me.typeTextBox.AutoCompleteMode = AutoCompleteMode.Suggest
                Me.typeTextBox.AutoCompleteSource = AutoCompleteSource.CustomSource
                Me.typeTextBox.AutoCompleteCustomSource = autoCompleteStringCollection
                If (Not Me.selectedTypeName Is Nothing) Then
                    Dim type As Type = typeProvider.GetType(Me.selectedTypeName)
                    If (Not type Is Nothing) Then
                        Me.typeTextBox.Text = Me.GetSimpleTypeFullName(type)
                    End If
                End If
            Catch exception1 As FileNotFoundException
            Finally
                Cursor.Current = Cursors.Default
            End Try
            Me.UpdateControlState
            Me.typeTextBox.Select
        End Sub

        Protected Overrides Sub OnPaint(ByVal paintArgs As PaintEventArgs)
            MyBase.OnPaint(paintArgs)
            Dim rectangle As New Rectangle(MyBase.ClientRectangle.Left, (Me.artifactLabel.Bottom + (((Me.typeNameTableLayoutPanel.Top + Me.typeTextBox.Top) - Me.artifactLabel.Bottom) / 2)), MyBase.ClientRectangle.Width, 1)
            paintArgs.Graphics.DrawLine(SystemPens.ControlDark, rectangle.Left, rectangle.Bottom, rectangle.Right, rectangle.Bottom)
            paintArgs.Graphics.DrawLine(SystemPens.ControlLightLight, rectangle.Left, (rectangle.Bottom + 1), rectangle.Right, (rectangle.Bottom + 1))
            rectangle = New Rectangle(MyBase.ClientRectangle.Left, (Me.helpTextHolder.Bottom + (((Me.okCancelTableLayoutPanel.Top + Me.buttonOK.Top) - Me.helpTextHolder.Bottom) / 2)), MyBase.ClientRectangle.Width, 1)
            paintArgs.Graphics.DrawLine(SystemPens.ControlDark, rectangle.Left, rectangle.Bottom, rectangle.Right, rectangle.Bottom)
            paintArgs.Graphics.DrawLine(SystemPens.ControlLightLight, rectangle.Left, (rectangle.Bottom + 1), rectangle.Right, (rectangle.Bottom + 1))
            paintArgs.Graphics.DrawLine(SystemPens.WindowFrame, (Me.helpTextHolder.Left - 1), (Me.helpTextHolder.Top - 1), (Me.helpTextHolder.Left - 1), Me.helpTextHolder.Bottom)
            paintArgs.Graphics.DrawLine(SystemPens.WindowFrame, (Me.helpTextHolder.Left - 1), Me.helpTextHolder.Bottom, Me.helpTextHolder.Right, Me.helpTextHolder.Bottom)
            paintArgs.Graphics.DrawLine(SystemPens.WindowFrame, Me.helpTextHolder.Right, Me.helpTextHolder.Bottom, Me.helpTextHolder.Right, (Me.helpTextHolder.Top - 1))
            paintArgs.Graphics.DrawLine(SystemPens.WindowFrame, Me.helpTextHolder.Right, (Me.helpTextHolder.Top - 1), (Me.helpTextHolder.Left - 1), (Me.helpTextHolder.Top - 1))
        End Sub

        Private Sub OnTreeSelectionChange(ByVal sender As Object, ByVal e As TreeViewEventArgs)
            Me.TreeSelectionChanged(e.Node)
        End Sub

        Private Sub OnTreeViewGotFocus(ByVal sender As Object, ByVal e As EventArgs)
            If Me.refreshTreeView Then
                Me.refreshTreeView = False
                If (Not Me.artifactTreeView.SelectedNode Is Nothing) Then
                    Me.TreeSelectionChanged(Me.artifactTreeView.SelectedNode)
                End If
            End If
        End Sub

        Private Sub OnTypeTextBoxSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            Me.OnTypeTextBoxTextChanged(sender, e)
        End Sub

        Private Sub OnTypeTextBoxTextChanged(ByVal sender As Object, ByVal e As EventArgs)
            Try 
                If Not Me.refreshTypeTextBox Then
                    Me.refreshTypeTextBox = True
                    Dim type As Type = Me.TypeProvider.GetType(Me.typeTextBox.Text)
                    If (Not type Is Nothing) Then
                        Me.lastComboboxValue = Me.typeTextBox.Text
                        Dim baseType As Type = Nothing
                        Dim parameterDataArray As ParameterData() = Nothing
                        Dim arrayRanks As Integer() = Nothing
                        Me.GetTypeParts(type, baseType, parameterDataArray, arrayRanks)
                        Me.genericParameters.Parameters = If((Not parameterDataArray Is Nothing), parameterDataArray, New ParameterData(0  - 1) {})
                        Me.genericParametersPropertyGrid.Refresh
                        Me.ListSelectionChanged(baseType)
                        Me.genericParametersPropertyGrid.Enabled = baseType.IsGenericTypeDefinition
                        Dim item As ListViewItem
                        For Each item In Me.artifactListView.Items
                            Dim tag As Type = [TryCast](item.Tag,Type)
                            If ((Not tag Is Nothing) AndAlso tag.FullName.Equals(baseType.FullName)) Then
                                If Not item.Selected Then
                                    item.Selected = True
                                End If
                                Exit For
                            End If
                            item.Selected = False
                        Next
                    Else
                        If (Me.artifactListView.SelectedItems.Count <> 0) Then
                            Me.artifactListView.SelectedItems.Item(0).Selected = False
                        End If
                        Me.genericParameters.Parameters = New ParameterData(0  - 1) {}
                        Me.genericParametersPropertyGrid.Enabled = False
                    End If
                    Me.UpdateControlState
                    Me.refreshTypeTextBox = False
                End If
            Catch exception As Exception
                DesignerHelpers.ShowError(Me.serviceProvider, exception)
            End Try
        End Sub

        <SecurityPermission(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.UnmanagedCode)> _
        Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
            If ((keyData = Keys.Return) AndAlso (Me.lastComboboxValue <> Me.typeTextBox.Text)) Then
                Me.lastComboboxValue = Me.typeTextBox.Text
                Me.typeTextBox.Text = String.Empty
                Me.typeTextBox.Text = Me.lastComboboxValue
                Me.typeTextBox.SelectionStart = Me.typeTextBox.Text.Length
                Return True
            End If
            Return MyBase.ProcessCmdKey((msg), keyData)
        End Function

        Private Sub SortListViewItems(ByVal columnIndex As Integer)
            If ((columnIndex >= 0) AndAlso (columnIndex < Me.artifactListView.Columns.Count)) Then
                Dim comparer As New ListItemComparer((columnIndex = 0), Me.sortListViewAscending)
                Me.artifactListView.ListViewItemSorter = comparer
                If (Me.artifactListView.SelectedItems.Count > 0) Then
                    Me.artifactListView.SelectedItems.Item(0).EnsureVisible
                End If
                Dim hWndHeader As IntPtr = NativeMethods.ListView_GetHeader(Me.artifactListView.Handle)
                Dim hdi As New HDITEM { _
                    .mask = 20 _
                }
                Dim i As Integer
                For i = 0 To Me.artifactListView.Columns.Count - 1
                    If NativeMethods.Header_GetItem(hWndHeader, i, hdi) Then
                        hdi.fmt = (hdi.fmt And -12289)
                        hdi.hbm = IntPtr.Zero
                        NativeMethods.Header_SetItem(hWndHeader, i, hdi)
                    End If
                Next i
                If NativeMethods.Header_GetItem(hWndHeader, columnIndex, hdi) Then
                    hdi.mask = 20
                    hdi.fmt = (hdi.fmt Or &H3000)
                    hdi.hbm = If(Me.sortListViewAscending, Me.bitmapSortUp, Me.bitmapSortDown)
                    NativeMethods.Header_SetItem(hWndHeader, columnIndex, hdi)
                End If
            End If
        End Sub

        Private Function System.IServiceProvider.GetService(ByVal serviceType As Type) As Object Implements IServiceProvider.GetService
            Dim typeProvider As Object = Nothing
            If (serviceType Is GetType(ITypeProvider)) Then
                typeProvider = Me.TypeProvider
            End If
            Return typeProvider
        End Function

        Private Sub TreeSelectionChanged(ByVal treeNode As TreeNode)
            Try 
                If Not Me.artifactListView.Focused Then
                    Me.artifactListView.Items.Clear
                    Me.artifactListView.ListViewItemSorter = Nothing
                    Dim text As String = Nothing
                    Dim list As New ArrayList
                    If (Not treeNode Is Me.artifactTreeView.Nodes.Item("CurrentProject")) Then
                        If (treeNode Is Me.artifactTreeView.Nodes.Item("ReferencedAssemblies")) Then
                            Dim node As TreeNode
                            For Each node In treeNode.Nodes
                                list.Add(node.Tag)
                            Next
                        ElseIf TypeOf treeNode.Tag Is Assembly Then
                            list.Add(treeNode.Tag)
                        Else
                            If (Not treeNode.Parent.Tag Is Nothing) Then
                                list.Add(treeNode.Parent.Tag)
                            End If
                            [text] = treeNode.Text
                        End If
                    End If
                    Dim type As Type
                    For Each type In Me.TypeProvider.GetTypes
                        Try 
                            Dim customAttributes As Object() = type.GetCustomAttributes(GetType(ObsoleteAttribute), False)
                            If ((Not customAttributes Is Nothing) AndAlso (customAttributes.Length > 0)) Then
                                goto Label_01D5
                            End If
                        Catch exception1 As Exception
                        End Try
                        If (((([text] Is Nothing) OrElse (type.Namespace = [text])) AndAlso (((list.Count = 0) AndAlso (type.Assembly Is Nothing)) OrElse list.Contains(type.Assembly))) AndAlso ((Me.typeFilterProvider Is Nothing) OrElse Me.typeFilterProvider.CanFilterType(type, False))) Then
                            Dim item As New ListViewItem { _
                                .Text = type.Name _
                            }
                            item.SubItems.Add(type.FullName)
                            item.Tag = type
                            item.ImageIndex = 0
                            Me.artifactListView.Items.Add(item)
                        End If
                    Label_01D5:
                    Next
                    Me.SortListViewItems(0)
                    Me.artifactListView.SelectedIndices.Clear
                    If (Me.artifactListView.Items.Count > 0) Then
                        Me.artifactListView.Items.Item(0).Selected = True
                    End If
                End If
            Catch exception As Exception
                DesignerHelpers.ShowError(Me.serviceProvider, exception)
            End Try
        End Sub

        Private Sub TypeBrowserDialog_HelpButtonClicked(ByVal sender As Object, ByVal e As CancelEventArgs)
            e.Cancel = True
            Me.GetHelp
        End Sub

        Private Sub UpdateControlState()
            Dim typeProvider As ITypeProvider = Me.TypeProvider
            Dim type As Type = Nothing
            type = typeProvider.GetType(Me.typeTextBox.Text)
            If (((Not type Is Nothing) AndAlso ((Me.typeFilterProvider Is Nothing) OrElse Me.typeFilterProvider.CanFilterType(type, False))) AndAlso Not type.IsGenericTypeDefinition) Then
                Me.buttonOK.Enabled = True
                MyBase.AcceptButton = Me.buttonOK
            Else
                Me.buttonOK.Enabled = False
                MyBase.AcceptButton = Nothing
            End If
            Me.helpTextWindow.UpdateHelpText(type)
        End Sub

        Private Sub UpdateTreeView(ByVal types As Type(), ByVal autoCompleteStringCollection As AutoCompleteStringCollection)
            Dim node As TreeNode = Me.artifactTreeView.Nodes.Item("ReferencedAssemblies")
            Dim hashtable As New Hashtable
            Dim type As Type
            For Each type In types
                If (((Me.typeFilterProvider Is Nothing) OrElse Me.typeFilterProvider.CanFilterType(type, False)) AndAlso Not autoCompleteStringCollection.Contains(type.FullName)) Then
                    autoCompleteStringCollection.Add(type.FullName)
                    Dim node2 As TreeNode = Nothing
                    If (Not type.Assembly Is Nothing) Then
                        node2 = [TryCast](hashtable.Item(type.Assembly),TreeNode)
                        If (node2 Is Nothing) Then
                            node2 = New TreeNode(type.Assembly.GetName.Name, 3, 3) { _
                                .Tag = type.Assembly _
                            }
                            node.Nodes.Add(node2)
                            hashtable.Item(type.Assembly) = node2
                        End If
                    Else
                        node2 = Me.artifactTreeView.Nodes.Item("CurrentProject")
                    End If
                    If ((Not type.Namespace Is Nothing) AndAlso (type.Namespace.Length > 0)) Then
                        Dim flag As Boolean = False
                        Dim text As String = type.Namespace
                        Dim node3 As TreeNode
                        For Each node3 In node2.Nodes
                            If (node3.Text = [text]) Then
                                flag = True
                                Exit For
                            End If
                        Next
                        If Not flag Then
                            Dim node4 As New TreeNode([text], &H31, &H31)
                            node2.Nodes.Add(node4)
                        End If
                    End If
                End If
            Next
        End Sub

        Private Sub UpdateTypeTextBox()
            Dim fullName As String = String.Empty
            If (Me.artifactListView.SelectedItems.Count > 0) Then
                Dim tag As Type = [TryCast](Me.artifactListView.SelectedItems.Item(0).Tag,Type)
                fullName = tag.FullName
                Dim flag As Boolean = True
                Dim str2 As String = String.Empty
                If (tag.IsGenericType AndAlso (Me.genericParameters.Parameters.Length > 0)) Then
                    str2 = "["
                    Dim num As Integer = 0
                    Dim data As ParameterData
                    For Each data In Me.genericParameters.Parameters
                        str2 = (str2 & "[")
                        num += 1
                        Dim type As Type = data.Type
                        If (Not type Is Nothing) Then
                            str2 = (str2 & type.FullName)
                        Else
                            flag = False
                            Exit For
                        End If
                        str2 = (str2 & "]")
                        If (num < Me.genericParameters.Parameters.Length) Then
                            str2 = (str2 & ",")
                        End If
                    Next
                    str2 = (str2 & "]")
                End If
                If flag Then
                    fullName = (fullName & str2)
                End If
            End If
            Me.typeTextBox.Text = fullName
        End Sub


        ' Properties
        Public ReadOnly Property SelectedType As Type
            Get
                Return Me.selectedType
            End Get
        End Property

        Private ReadOnly Property System.ComponentModel.ISite.Component As IComponent
            Get
                Return Nothing
            End Get
        End Property

        Private ReadOnly Property System.ComponentModel.ISite.Container As IContainer
            Get
                Return Nothing
            End Get
        End Property

        Private ReadOnly Property System.ComponentModel.ISite.DesignMode As Boolean
            Get
                Return True
            End Get
        End Property

        Private Property System.ComponentModel.ISite.Name As String
            Get
                Return ""
            End Get
            Set(ByVal value As String)
            End Set
        End Property

        Private ReadOnly Property TypeProvider As ITypeProvider
            Get
                Dim localTypeProvider As ITypeProvider = Me.localTypeProvider
                If (localTypeProvider Is Nothing) Then
                    localTypeProvider = DirectCast(Me.serviceProvider.GetService(GetType(ITypeProvider)), ITypeProvider)
                End If
                If (localTypeProvider Is Nothing) Then
                    Throw New InvalidOperationException(SR.GetString("General_MissingService", New Object() { GetType(ITypeProvider).FullName }))
                End If
                Return localTypeProvider
            End Get
        End Property


        ' Fields
        Private advancedTabPage As TabPage
        Private artifactImages As ImageList
        Private artifactLabel As TextBox
        Private artifactListView As ListView
        Private artifactTreeView As TreeView
        Private bitmapSortDown As IntPtr
        Private bitmapSortUp As IntPtr
        Private buttonBrowse As Button
        Private buttonCancel As Button
        Private buttonOK As Button
        Private fullyQualifiedName As ColumnHeader
        Private genericParameters As GenericParameters
        Private genericParametersPropertyGrid As PropertyGrid
        Private helpTextHolder As TextBox
        Private helpTextWindow As HelpTextWindow
        Private lastComboboxValue As String
        Private localTypeProvider As TypeProvider
        Private okCancelTableLayoutPanel As TableLayoutPanel
        Private refreshTreeView As Boolean
        Private refreshTypeTextBox As Boolean
        Private Shared ResMgr As ResourceManager = New ResourceManager("System.Workflow.ComponentModel.Design.ArtifactReference", Assembly.GetExecutingAssembly)
        Private selectedType As Type
        Private selectedTypeName As String
        Private serviceProvider As IServiceProvider
        Private sortListViewAscending As Boolean
        Private tabControl As TabControl
        Private typeFilterProvider As ITypeFilterProvider
        Private typeName As ColumnHeader
        Private typeNameLabel As Label
        Private typeNameTableLayoutPanel As TableLayoutPanel
        Private typeSplitContainer As SplitContainer
        Private typeTabPage As TabPage
        Private typeTextBox As TextBox

        ' Nested Types
        Private Class DummySite
            Implements ISite, IServiceProvider
            ' Methods
            Friend Sub New(ByVal serviceProvider As IServiceProvider)
                Me.serviceProvider = serviceProvider
            End Sub

            Public Function GetService(ByVal type As Type) As Object
                Return Me.serviceProvider.GetService(type)
            End Function


            ' Properties
            Public ReadOnly Property Component As IComponent
                Get
                    Return Nothing
                End Get
            End Property

            Public ReadOnly Property Container As IContainer
                Get
                    Return Nothing
                End Get
            End Property

            Public ReadOnly Property DesignMode As Boolean
                Get
                    Return True
                End Get
            End Property

            Public Property Name As String
                Get
                    Return String.Empty
                End Get
                Set(ByVal value As String)
                End Set
            End Property


            ' Fields
            Private serviceProvider As IServiceProvider
        End Class

        <TypeConverter(GetType(GenericParametersConverter))> _
        Private Class GenericParameters
            ' Properties
            Public Property Parameters As ParameterData()
                Get
                    Return Me.parameters
                End Get
                Set(ByVal value As ParameterData())
                    Me.parameters = value
                End Set
            End Property


            ' Fields
            Private parameters As ParameterData() = New ParameterData(0  - 1) {}
        End Class

        Private Class GenericParametersConverter
            Inherits TypeConverter
            ' Methods
            Public Overrides Function GetProperties(ByVal context As ITypeDescriptorContext, ByVal value As Object, ByVal attributes As Attribute()) As PropertyDescriptorCollection
                Dim descriptors As New PropertyDescriptorCollection(Nothing)
                Dim parameters As GenericParameters = [TryCast](value,GenericParameters)
                Dim data As ParameterData
                For Each data In parameters.Parameters
                    descriptors.Add(New ParameterDataPropertyDescriptor(context, TypeDescriptor.CreateProperty(GetType(GenericParameters), data.ParameterType.Name, GetType(ParameterData), New Attribute(0  - 1) {})))
                Next
                Return descriptors
            End Function

            Public Overrides Function GetPropertiesSupported(ByVal context As ITypeDescriptorContext) As Boolean
                Return True
            End Function

        End Class

        Private NotInheritable Class HelpTextWindow
            Inherits RichTextBox
            ' Methods
            Friend Sub New()
                MyBase.TabStop = False
                MyBase.BorderStyle = BorderStyle.None
                MyBase.ReadOnly = True
                Me.BackColor = SystemColors.Control
                Me.Multiline = True
                MyBase.ScrollBars = RichTextBoxScrollBars.Both
                Me.Cursor = Cursors.Default
            End Sub

            Friend Sub UpdateHelpText(ByVal selectedType As Type)
                [Using] font As Font = New Font(Me.Font.FontFamily, Me.Font.SizeInPoints, FontStyle.Bold)
                    MyBase.Clear
                    If (Not selectedType Is Nothing) Then
                        Dim strArray As String() = New String(3  - 1) {}
                        strArray(0) = selectedType.Name
                        Try 
                            strArray(1) = If(((Not selectedType.Namespace Is Nothing) AndAlso (selectedType.Namespace.Length > 0)), selectedType.Namespace, TypeBrowserDialog.ResMgr.GetString("IDS_GLOBALNS"))
                        Catch exception1 As NullReferenceException
                        End Try
                        strArray(1) = ("{" & strArray(1) & "}")
                        strArray(2) = If((Not selectedType.Assembly Is Nothing), selectedType.Assembly.GetName.FullName, "<Current Project>")
                        Dim colorArray As Color() = New Color() { Color.DarkRed, Color.Green, Color.Blue }
                        Me.Text = String.Concat(New String() { TypeBrowserDialog.ResMgr.GetString("IDS_SELECTEDTYPE"), " ", strArray(0), " ", TypeBrowserDialog.ResMgr.GetString("IDS_MEMBEROF"), " ", strArray(1), ChrW(13) & ChrW(10), TypeBrowserDialog.ResMgr.GetString("IDS_CONTAINEDINASM"), " ", strArray(2) })
                        Dim start As Integer = 0
                        Dim i As Integer
                        For i = 0 To strArray.GetLength(0) - 1
                            start = MyBase.Find(strArray(i), start, (RichTextBoxFinds.MatchCase Or RichTextBoxFinds.WholeWord))
                            MyBase.SelectionColor = colorArray(i)
                            MyBase.SelectionFont = font
                            start = (start + strArray(i).Length)
                        Next i
                    Else
                        Me.Text = TypeBrowserDialog.ResMgr.GetString("IDS_NOTYPESSELECTED")
                        MyBase.SelectionStart = 0
                        Me.SelectionLength = Me.Text.Length
                        MyBase.SelectionColor = Color.DarkRed
                        MyBase.SelectionFont = font
                    End If
                End [Using]
            End Sub

            Protected Overrides Sub WndProc(ByRef msg As Message)
                If ((msg.Msg < &H200) OrElse (msg.Msg > &H20D)) Then
                    MyBase.WndProc((msg))
                End If
            End Sub

        End Class

        Private NotInheritable Class ListItemComparer
            Implements IComparer
            ' Methods
            Friend Sub New(ByVal compareTypeName As Boolean, ByVal ascending As Boolean)
                Me.compareTypeName = compareTypeName
                Me.ascending = ascending
            End Sub

            Public Function [Compare](ByVal first As Object, ByVal second As Object) As Integer
                Dim num As Integer = 0
                If Me.compareTypeName Then
                    num = String.Compare(DirectCast(first, ListViewItem).Text, DirectCast(second, ListViewItem).Text)
                Else
                    num = String.Compare(DirectCast(first, ListViewItem).SubItems.Item(1).Text, DirectCast(second, ListViewItem).SubItems.Item(1).Text)
                End If
                If Not Me.ascending Then
                    Return (-1 * num)
                End If
                Return num
            End Function


            ' Fields
            Private ascending As Boolean
            Private compareTypeName As Boolean
        End Class

        Private Class ParamaeterDataConverter
            Inherits TypeConverter
            ' Methods
            Public Overrides Function CanConvertFrom(ByVal context As ITypeDescriptorContext, ByVal sourceType As Type) As Boolean
                Return ((sourceType Is GetType(String)) OrElse MyBase.CanConvertFrom(context, sourceType))
            End Function

            Public Overrides Function CanConvertTo(ByVal context As ITypeDescriptorContext, ByVal destinationType As Type) As Boolean
                Return ((destinationType Is GetType(String)) OrElse MyBase.CanConvertTo(context, destinationType))
            End Function

            Public Overrides Function ConvertFrom(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object) As Object
                If (value Is Nothing) Then
                    Return New ParameterData
                End If
                If Not TypeOf value Is String Then
                    Return MyBase.ConvertFrom(context, culture, value)
                End If
                Dim data As New ParameterData
                If (CStr(value) <> String.Empty) Then
                    data.Type = [TryCast](context.GetService(GetType(ITypeProvider)),ITypeProvider).GetType([TryCast](value,String), True)
                End If
                Return data
            End Function

            Public Overrides Function ConvertTo(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object, ByVal destinationType As Type) As Object
                If (destinationType Is GetType(String)) Then
                    Dim data As ParameterData = [TryCast](value,ParameterData)
                    If (Not data.Type Is Nothing) Then
                        Return data.Type.AssemblyQualifiedName
                    End If
                    Return String.Empty
                End If
                If (destinationType Is Nothing) Then
                    Return String.Empty
                End If
                Return MyBase.ConvertTo(context, culture, value, destinationType)
            End Function

        End Class

        <Editor(GetType(TypeBrowserEditor), GetType(UITypeEditor)), TypeConverter(GetType(ParamaeterDataConverter))> _
        Private NotInheritable Class ParameterData
            Implements ITypeFilterProvider
            ' Methods
            Public Function CanFilterType(ByVal type As Type, ByVal throwOnError As Boolean) As Boolean
                Dim flag As Boolean = True
                If (type.IsByRef OrElse Not TypeProvider.IsAssignable(Me.parameterType.BaseType, type)) Then
                    flag = False
                End If
                If (throwOnError AndAlso Not flag) Then
                    Throw New Exception(SR.GetString("Error_ArgumentTypeNotMatchParameter"))
                End If
                Return flag
            End Function


            ' Properties
            Public ReadOnly Property FilterDescription As String
                Get
                    Return SR.GetString("FilterDescription_GenericArgument", New Object() { Me.parameterType.Name })
                End Get
            End Property

            Public Property ParameterType As Type
                Get
                    Return Me.parameterType
                End Get
                Set(ByVal value As Type)
                    Me.parameterType = value
                End Set
            End Property

            Public Property Type As Type
                Get
                    Return Me.type
                End Get
                Set(ByVal value As Type)
                    Me.type = value
                End Set
            End Property


            ' Fields
            Private parameterType As Type
            Private type As Type
        End Class

        Private Class ParameterDataPropertyDescriptor
            Inherits PropertyDescriptor
            ' Methods
            Friend Sub New(ByVal serviceProvider As IServiceProvider, ByVal desc As PropertyDescriptor)
                MyBase.New(desc, Nothing)
                Me.realPropertyDescriptor = desc
                Me.serviceProvider = serviceProvider
            End Sub

            Public Overrides Function CanResetValue(ByVal component As Object) As Boolean
                Return Me.realPropertyDescriptor.CanResetValue(component)
            End Function

            Public Overrides Function GetValue(ByVal component As Object) As Object
                Dim parameters As GenericParameters = [TryCast](component,GenericParameters)
                Dim data As ParameterData
                For Each data In parameters.Parameters
                    If (data.ParameterType.Name = Me.Name) Then
                        Return data
                    End If
                Next
                Return Nothing
            End Function

            Public Overrides Sub ResetValue(ByVal component As Object)
                Me.realPropertyDescriptor.ResetValue(component)
            End Sub

            Public Overrides Sub SetValue(ByVal component As Object, ByVal value As Object)
                Dim parameters As GenericParameters = [TryCast](component,GenericParameters)
                Dim data As ParameterData
                For Each data In parameters.Parameters
                    If (data.ParameterType.Name = Me.Name) Then
                        data.Type = DirectCast(value, ParameterData).Type
                        Return
                    End If
                Next
            End Sub

            Public Overrides Function ShouldSerializeValue(ByVal component As Object) As Boolean
                Return Me.realPropertyDescriptor.ShouldSerializeValue(component)
            End Function


            ' Properties
            Public Overrides ReadOnly Property Attributes As AttributeCollection
                Get
                    Return Me.realPropertyDescriptor.Attributes
                End Get
            End Property

            Public Overrides ReadOnly Property Category As String
                Get
                    Return SR.GetString("GenericParameters")
                End Get
            End Property

            Public Overrides ReadOnly Property ComponentType As Type
                Get
                    Return Me.realPropertyDescriptor.ComponentType
                End Get
            End Property

            Public Overrides ReadOnly Property Converter As TypeConverter
                Get
                    Return Me.realPropertyDescriptor.Converter
                End Get
            End Property

            Public Overrides ReadOnly Property Description As String
                Get
                    Return Me.realPropertyDescriptor.Description
                End Get
            End Property

            Public Overrides ReadOnly Property IsReadOnly As Boolean
                Get
                    Return False
                End Get
            End Property

            Public Overrides ReadOnly Property PropertyType As Type
                Get
                    Return Me.realPropertyDescriptor.PropertyType
                End Get
            End Property


            ' Fields
            Private realPropertyDescriptor As PropertyDescriptor
            Private serviceProvider As IServiceProvider
        End Class
    End Class
End Namespace

